package com.sita.tboard;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sita.bike.R;
import com.sita.bike.support.Constants;
import com.sita.bike.support.Foreground;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.ui.activity.LoginActivity;
import com.sita.bike.utils.SessionUtils;
import com.sita.tboard.advertisement.AdDetailActivity;
import com.sita.tboard.advertisement.AdModel;
import com.sita.tboard.advertisement.AdvertiseManager;
import com.sita.tboard.hitchhike.pick.DriverNotificationDialog;
import com.squareup.picasso.Picasso;

/**
 * Created by xiaodong on 16/3/4.
 */
public abstract class ActivityBase extends AppCompatActivity {

    private ActivityBase thisActivity;

    private CountDownTimer countDownTimer;

    protected Foreground.Listener myListener = new Foreground.Listener() {
        public void onBecameForeground() {
            doInForeground();
        }

        public void onBecameBackground() {
            String appStateStr = thisActivity.getIntent().getStringExtra(Constants.BUNDLE_APP_STATE);
            if (!TextUtils.isEmpty(appStateStr)) {
                AdvertiseManager.AppState appState = AdvertiseManager.AppState.valueOf(appStateStr);
                AdvertiseManager.getInstance().setAppState(appState);
                thisActivity.getIntent().removeExtra(Constants.BUNDLE_APP_STATE);
            } else {
                AdvertiseManager.getInstance().setAppState(AdvertiseManager.AppState.IN_BACKGROUND);
            }
            doInBackground();
        }
    };

    private void doInBackground() {
        AdvertiseManager.getInstance().downloadAdvertise();
    }

    private void doInForeground() {
        AdModel adModel = AdvertiseManager.getInstance().getAdModel();
        if ((adModel == null) || adModel.playCount > 0) {
            AdvertiseManager.getInstance().setAdShow(true);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Foreground.get(this).addListener(myListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Foreground.get(this).removeListener(myListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!SessionUtils.isLoggedIn(null)) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            if (thisActivity != null && !thisActivity.isFinishing()) {
                thisActivity.finish();
            }
        } else {
            thisActivity = this;
            AdvertiseManager.getInstance().setAppState(AdvertiseManager.AppState.IN_FOREGROUND);
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        AdvertiseManager.AppState prevState = AdvertiseManager.getInstance().getPrevState();
        if (AdvertiseManager.getInstance().canAdShow()) {
            showAdView();
        }
    }

    private void showAdView() {
        LayoutInflater inflater = LayoutInflater.from(GlobalContext.getGlobalContext());

        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        // 设置window type
        params.type = WindowManager.LayoutParams.TYPE_PHONE;
        params.format = PixelFormat.RGBA_8888;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        //加载需要的XML布局文件
        final RelativeLayout mInView = (RelativeLayout) inflater.inflate(R.layout.activity_adshow, null, false);

        final TextView timerView = (TextView) mInView.findViewById(R.id.timer);
        final ImageView bigpicView = (ImageView) mInView.findViewById(R.id.big_pic);

        AdModel adModel = AdvertiseManager.getInstance().getAdModel();
        if (adModel != null) {
            Picasso.with(GlobalContext.getGlobalContext()).load(adModel.bitmap).fit().centerInside().into(bigpicView);
            bigpicView.setClickable(true);
        } else {
            bigpicView.setClickable(false);
        }

        final WindowManager wm = (WindowManager) GlobalContext.getGlobalContext()
                .getSystemService(Context.WINDOW_SERVICE);
        countDownTimer = new CountDownTimer(Constants.ADVERTISEMENT_SHOW_TIME,
                Constants.ADVERTISEMENT_INTERVAL) {
            @Override
            public void onTick(long l) {
                String time = String.valueOf((int) Math.round(l / 1000.0) - 1);
                timerView.setText(time);
            }

            @Override
            public void onFinish() {
                if (mInView.getParent() != null) {
                    wm.removeView(mInView);
                    countDownTimer = null;
                }
            }
        };
        countDownTimer.start();

        bigpicView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AdvertiseManager.getInstance().getAdModel() == null) {
                    return;
                }
                Intent intent = new Intent(thisActivity, AdDetailActivity.class);
                thisActivity.startActivity(intent);
                if (mInView.getParent() != null) {
                    wm.removeView(mInView);
                }
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                    countDownTimer = null;
                }
            }
        });

        //添加到WindowManager里面
        if (mInView.getParent() == null) {
            wm.addView(mInView, params);
            AdvertiseManager.getInstance().setAdShow(false);
            AdvertiseManager.getInstance().setPreAdShowTime(SystemClock.elapsedRealtime());
            AdvertiseManager.getInstance().decreasePlayCount();
        }
    }

    protected void exitAppComplete() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            this.finishAffinity();
        } else {
            this.finish();
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    /*public void onEventMainThread(CallcarReceivedEvent event) {
        CallcarBean callcarBean = event.getCallcarBean();

        DriverNotificationDialog dialog = new DriverNotificationDialog(this, callcarBean);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }*/

    /*public void onEventMainThread(final HitchhikePayReceivedEvent event) {
        final String money = NumberUtils.formatCurrency(event.getMoney());
        UserNetworkHelper.getInstance().getUserInfo(event.getAccountid(), new GetAccountInfoListener() {
            @Override
            public void onSuccess(Account account) {
                String alertMsg = GlobalContext.getGlobalContext()
                        .getString(R.string.received_payment_from_customer, account.mNickName, money);
                ToastUtils.show(GlobalContext.getGlobalContext(), alertMsg);
                CcTicketEntity ticketEntity = PersistUtils.getTicket(Long.valueOf(event.getRentTripId()));
                if (ticketEntity != null){
                    ticketEntity.setMoney(event.getMoney().floatValue());
                    PersistUtils.saveTicket(ticketEntity);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {

            }
        });
    }*/
}
